//index.js
//获取应用实例
const app = getApp()

var QQMapWX = require('../../libs/qqmap-wx-jssdk.js')
var qqmapsdk

const config = require('../../config/config.js')
const util = require('../../utils/util.js')

Page({
  data: {
    // motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),

    downArrow: "./../../imgs/down.png",
    upArrow: "./../../imgs/up.png",

    // 轮播图参数
    background: ['demo-text-1', 'demo-text-2', 'demo-text-3'],
    // bannerImgs: [
    //   "./../../imgs/banner/banner01.jpg",
    //   "./../../imgs/banner/banner02.jpg",
    //   "./../../imgs/banner/banner03.jpg",
    // ],
    // bannerUrls: [],
    bannersInfo: [],
    indicatorDots: true,
    vertical: false,
    autoplay: true,
    circular: true,
    interval: 3000,
    duration: 500,
    previousMargin: 0,
    nextMargin: 0,

    // 菜系及排序方式选择
    currentPanelNum: 0,
    // currentFoodStyle: "全部",
    // currentOrderStyle: "按时间排序",
    foodStyles: config.foodStyles,
    currentFoodStyleIndex: 0,
    orderStyles: config.foodOrderStyles,
    currentOrderStyleIndex: 0,
    foods: [],
    startLoading: false,
    currentPage: 1,
    loading: false,
    alreadyBottom: false,
    bottomLoading: false,
    foodStyle: '',
    orderRule: 'create_time',

    reload: false
    
  },

  onLoad: function () {

    this.loadingStartFoodsInfo()

    this.getBannersInfo().then(data => {
      if (data.length > 0) {
        this.setData({
          bannersInfo: data
        })
      }
    })

    this.getFoodStyles().then(res => {
      if (res.code == 1) {
        let foodStyles = ['所有菜系']
        for (let i=0,length=res.data.length; i < length; i++) {
          foodStyles.push(res.data[i].food_style)
        }
        // console.log(foodStyles)
        this.setData({
          foodStyles: foodStyles
        })
      }
    })
  },


  getFoodStyles: function() {
    return new Promise(resolve => {
      wx.request({
        url: `${config.requestBaseUrl}/Dishes/getFoodStyles`,
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          // console.log(res)
          resolve(res.data)
        }
      })
    })
  },

  getBannersInfo: function() {
    return new Promise(resolve => {
      wx.request({
        url: `${config.requestBaseUrl}/Index/getBannerInfo`,
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          resolve(res.data)
        }
      })
    })
  },


  getUserInfo: function(e) {
    // console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "美食青城",
      desc: "青城的美食都在这里！",
      path: "pages/index/index"
    }
  },

  loadingStartFoodsInfo: function() {
    this.setData({
      startLoading: true
    })
    this.refreshFoodsInfo(this.data.currentPage).then((res) => {
      this.setData({
        startLoading: false,
        foods: res
      })
    })
  },

  onPullDownRefresh: function() {
    // console.log(this.loading)
    let that = this
    if (!this.data.loading) {
      this.setData({
        loading: true,
        currentPage: 1
      })
      this.refreshFoodsInfo(this.data.currentPage).then(function(res) {
        that.setData({
          foods: res,
          loading: false,
          alreadyBottom: false,
        })
        wx.stopPullDownRefresh()
      })
    } else {
      wx.stopPullDownRefresh()
    }
  },

  onReachBottom: function() {
    // console.log(this.data.currentPage)
    let that = this
    if (!this.data.alreadyBottom && !this.data.bottomLoading) {
      this.setData({
        bottomLoading: true
      })
      this.refreshFoodsInfo(this.data.currentPage + 1).then(function (res) {
        // console.log(res)
        if (res.length === 0) {
          that.setData({
            bottomLoading: false,
            alreadyBottom: true
          })
        } else {
          that.setData({
            foods: that.data.foods.concat(res),
            currentPage: that.data.currentPage + 1,
            bottomLoading: false
          })
        }
      })
    }
    
  },

  refreshFoodsInfo: function(currentPage) {
    let that = this
    return new Promise(resolve => {
      wx.getLocation({
        success: function (res) {
          that.getFoodsInfoAsync(res.latitude, res.longitude, currentPage, that.data.foodStyle, that.data.orderRule).then(res => {
            let data = res.data
            for (let i = 0, len = data.length; i < len; i++) {
              let distance = data[i]['distance']
              data[i]['distance'] = distance < 1 ? Math.round(distance * 1000) + 'm' : Math.round(distance * 10) / 10 + 'km'
            }
            resolve(data)
          })
        },
        fail: function () {
          that.setData({
            reload: true,
            startLoading: false
          })
          util.getUserLocation(function(){
            that.setData({
              reload: true,
              startLoading: false
            })
          })
        }
      })
    })
  },

  onShow: function () {
    // console.log(`here is onShow${this.data.reload}`)
    if (this.data.reload) {
      this.loadingStartFoodsInfo()
      this.setData({
        reload: false
      })
    }
  },

  getLocationAsync: function() {
    return new Promise(resolve => {
      wx.getLocation({
        success: function(res) {
          resolve(res)
        },
        fail: function() {
          util.getUserLocation().then(res => {
            resolve(res)
          })
        }
      })
    })
  },

  getFoodsInfoAsync: function (latitude, longitude, currentPage, foodStyle, orderRule) {
    return new Promise(resolve => {
      wx.request({
        url: `${config.requestBaseUrl}/Dishes/getFoods`,
        method: 'POST',
        data: {
          latitude: latitude,
          longitude: longitude,
          page: currentPage,
          openid: wx.getStorageSync('openid'),
          key_word: '',
          food_style: foodStyle,
          order_rule: orderRule
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          // console.log(res)
          resolve(res)
        }
      })
    })
  },

  // getFoodsInfo: function (latitude, longitude) {
  //   let that = this
  //   wx.request({
  //     url: `${config.requestBaseUrl}/Dishes/getFoods`,
  //     method: 'POST',
  //     data: {
  //       latitude: latitude,
  //       longitude: longitude
  //     },
  //     header: {
  //       'content-type': 'application/x-www-form-urlencoded'
  //     },
  //     success: function (res) {
  //       // console.log(res)
  //       // this.loading = false
  //       let data = res.data
  //       for (let i=0, len=data.length; i<len; i++) {
  //         let distance = data[i]['distance']
  //         data[i]['distance'] = distance < 1 ? Math.round(distance*1000)+'m' : Math.round(distance*10)/10+'km'
  //       }
  //       that.setData({
  //         foods: data
  //       })
        
  //     }
  //   })

  // },

  getUserLocation: function () {
    let getUserCityInfo = this.getUserCityInfo
    wx.getLocation({
      success: function(res) {
        console.log(res)
        getUserCityInfo({
          latitude: res.latitude,
          longitude: res.longitude
        })
      },
    })
    // console.log(qqmapsdk)
    // qqmapsdk.search({
    //   keyword: 'xiaochengxudemo',
    //   success: function (res) {
    //     console.log(res)
    //   },
    //   fail: function(res) {
    //     console.log(res)
    //   }
    // })
  },

  getUserCityInfo: function(data) {
    qqmapsdk.reverseGeocoder({
      location: data,
      success: function(res) {
        console.log(res)
      },
      fail: function(res) {
        console.log(res)
      }
    })
  },

  goToSearch: function() {
    wx.navigateTo({
      url: '../search/search',
    })
  },

  selectStyle: function(event) {
    let index = event.currentTarget.dataset.panelindex
    if (index == this.data.currentPanelNum) {
      this.setData({
        currentPanelNum: 0
      })
    } else {
      this.setData({
        currentPanelNum: index
      })
    }
  },

  clickMask: function() {
    this.setData({
      currentPanelNum: 0
    })
  },

  selectFoodStyle(event) {
    let index = event.currentTarget.dataset.index
    this.setData({
      currentPanelNum: 0,
    })
    if (index == this.data.currentFoodStyleIndex) {
      return
    }
    this.setData({
      currentPage: 1,
      currentFoodStyleIndex: index,
      foodStyle: index == 0 ? '' : this.data.foodStyles[index],
      startLoading: true,
      alreadyBottom: false,
      bottomLoading: false
    })
    this.refreshFoodsInfo(this.data.currentPage).then(res => {
      this.setData({
        startLoading: false,
        foods: res
      })
    })
  },

  selectOrderStyle(event) {
    let index = event.currentTarget.dataset.index
    this.setData({
      currentPanelNum: 0,
    })
    if (index == this.data.currentOrderStyleIndex) {
      return
    }
    this.setData({
      currentPage: 1,
      currentOrderStyleIndex: index,
      orderRule: config.orderRuleMap.get(this.data.orderStyles[index]),
      startLoading: true,
      alreadyBottom: false,
      bottomLoading: false
    })
    this.refreshFoodsInfo(this.data.currentPage).then(res => {
      this.setData({
        startLoading: false,
        foods: res
      })
    })
  },

  clickCollect: function(event) {
    // console.log(event)
    let that = this
    let foodId = event.currentTarget.dataset.id
    let index = event.currentTarget.dataset.index
    wx.request({
      url: `${config.requestBaseUrl}/Collect/CollectFood`,
      method: 'POST',
      data: {
        food_id: foodId,
        openid: wx.getStorageSync('openid')
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        // console.log(res)
        if (res.data.code != 0) {
          let foods = that.data.foods
          foods[index].is_collect = res.data.code === 1 ? 1 : 0
          foods[index].collect_num = res.data.code === 1 ? parseInt(foods[index].collect_num) + 1 : parseInt(foods[index].collect_num) - 1
          that.setData({
            foods: foods
          })
        }
      }
    })
  },


  // userOpenSetting: function() {
  //   wx.openSetting({
  //     success: res => {
  //       console.log(res)
  //     },
  //     fail: res => {
  //       console.log(res)
  //     }
  //   })
  // },

  openCommentsPage: function(event) {
    let foodId = event.currentTarget.dataset.foodid
    wx.navigateTo({
      url: `../commentsshow/commentsshow?food_id=${foodId}`,
    })
  },


  openDishLocation: function (event) {
    let latitude = event.currentTarget.dataset.latitude
    let longitude = event.currentTarget.dataset.longitude
    wx.openLocation({
      latitude: Number(latitude),
      longitude: Number(longitude)
    })
  },

  clickBanner: function (event) {
    let url = event.currentTarget.dataset.url
    // console.log(url)
    wx.navigateTo({
      url: url,
    })
  }



})
